<?php

//    Socket PHP Class.
//	  Turning Sockets OO, and making them a lot more enjoyable to work with..

//    Copyright (C) 2009 Kirth 'Sebastian'.
//
//    This code is property of the CodeArray PHP project.  Rights Reserved!
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

class Socket
{
	private $socket;
	
	static $host;
	static $port;
	
	public $connected = false;
	
	function __construct($host, $port, $silent = false) {
		$this->host = $host;
		$this->port = $port;
		$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
		if(!$socket) return false;
		if(!@socket_connect($socket, $host, $port)) {
			echo '[SOCK] > ERR: ' . sock_strerror(socket_last_error($this->socket)) . "\r\n";
			return false;
		}
		if(!$silent) echo '[SOCK] > Connection successful!' . "\r\n";
		$this->host = $host;
        $this->port = $port;
        $this->connected = true;
        $this->socket = $socket;
		$this->connected = true;
	}
	
	function __destruct() {
		if(isset($this->socket)) {
			socket_close($this->socket);
			unset($this->socket);
			echo '[SOCK] > Closed.' . "\r\n";
		}
	}
	
	function Write($buffer) {
		if(isset($this->socket)) {
			socket_write($this->socket, $buffer);
			return true;
		}
		
		return false;
	}
	
	function Read() {
		if(!isset($this->socket)) return false;
		else return @socket_read($this->socket, 128, PHP_BINARY_READ);
	}
	
	function IsConnected() {
		return $this->connected;
	}
	
	function Close() {
		if(isset($this->socket)) {
			socket_close($this->socket);
			unset($this->socket);
		}
	}
}

?>